package com.ht.api.task;

import javax.sql.DataSource;

import com.ht.api.db.Db;
import com.ht.api.db.DbConfig;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.db.task.HtTaskExecutor;
import com.ht.api.db.task.TaskHandler;
import com.ht.api.service.SopService;

import cn.hutool.json.JSONObject;

public class SopTimerTask implements TaskHandler {

	@Override
	public String getName() {
		return "刷新所有租户的旅程用户";
	}

	@Override
	public boolean handler(JSONObject requestParam, String groupId, long taskId) {
		DbList list = Db.createSqlParser("sys_tenant").query();
		list.stream().forEach(b -> {
			HtTaskExecutor.execute(() -> {
				Long tenantId = b.getLong("main_id");
				DataSource ds = DbConfig.tenantDSMap.get(tenantId);
		        StreamLoadConfig config = DbConfig.useTenantSLC(tenantId);
				
				//找到正常状态的旅程列表
		        DbList sopList = Db.createSqlParser("sop").where("status", 1).query(ds);

		        for (Entity sop : sopList) {
		            //判断旅程是否已经到了可刷新的时间
		            if (!SopService.isOverDays(sop.getStr("refresh_time"), sop.getInt("refresh_days"))) {
		                continue;
		            }

		            // 刷新旅程
		            SopService.refreshSopUser(ds, config, sop, false);
		        }
				
			});
		});
		
		return true;
	}

}
